#include <pthread.h>
#include <iostream>
#include <unistd.h>

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

int ticket = 1000;
void *Routine(void *arg)
{
    char* id = static_cast<char*>(arg);
    while(1)
    {
        pthread_mutex_lock(&lock);
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket : %d\n", id, ticket);
            ticket--;
            pthread_mutex_unlock(&lock);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_t t1, t2, t3, t4;
    pthread_create(&t1, nullptr, Routine, (void *)"thread-1");
    pthread_create(&t2, nullptr, Routine, (void *)"thread-2");
    pthread_create(&t3, nullptr, Routine, (void *)"thread-3");
    pthread_create(&t4, nullptr, Routine, (void *)"thread-4");


    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}